package com.birdboot.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    private String Uri;
    private String type;
    private String version;
    private String Head;
    private String requestPath;
    private Map<String,String> HttpMap = new HashMap<>();
    private Map<String,String> paramValue = new HashMap<>();

    public String getRequestPath() {
        return requestPath;
    }

    public void setRequestPath(String requestPath) {
        this.requestPath = requestPath;
    }

    public HttpServletRequest(@org.jetbrains.annotations.NotNull Socket socket) throws IOException {
        this.socket = socket;
        getLine();
    }

    public String getUri() {
        return Uri;
    }

    public String getType() {
        return type;
    }

    public String getVersion() {
        return version;
    }

    public String getHead(String strKey) {
        return HttpMap.get(strKey);
    }

    public String getParam(String name){
        return paramValue.get(name);
    }
    private void getLine() throws IOException {
        HttpMap.clear();
        InputStream in = socket.getInputStream();
        BufferedReader inBuffer = new BufferedReader(new InputStreamReader(in));
        int number= 0;
        while (true)
        {
           String lineStr = inBuffer.readLine().trim();
            System.out.println("接收到的数据"+lineStr);
            if(lineStr=="" || lineStr.isEmpty())
            {
                break;
            }
           if(number==0)
           {
                String []strData = lineStr.split("\\s");
                type = strData[0];
                Uri = strData[1];
                System.out.println(type+" "+ Uri);
                if(type.equals("GET") && Uri.indexOf("?")>0)
                {
                    System.out.println("111111111111111111111111111");
                    String [] data = Uri.split("\\?");
                    if(data.length>0){
                        Uri = data[0];
                    }
                    if (data.length>1){
                        String [] params = data[1].split("&");
                        if(params.length>0){
                            for (String item : params){
                                String []kv = item.split("=");
                                paramValue.put(kv[0],kv[1]);
                            }
                        }
                    }
                }
               version = strData[2];
           }else {
               String[] strData = lineStr.split(":\\s");
               this.HttpMap.put(strData[0],strData[1]);
           }
           number++;

        }

    }
}
